<template>
  <div id="shop-list" class="pay-list">
    <div class="search-box">
      <Row type="flex" justify="space-between">
        <Row type="flex">
          <Col class="search-item">
            <span class="search-label">组织名称:</span>
            <Input v-model="searchObj.searchKey" @on-keyup="filterSpace" :maxlength="20" placeholder="输入门店、区域、编码"></Input>
          </Col>
          <Col class="search-item">
            <span class="search-label">类型:</span>
            <Select v-model="type" class="select-shop-item" style="width:180px" @on-change='search'>
              <Option v-for="(item, i) in typeList" :value="item" :key="i">{{ item }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">状态:</span>
            <Select v-model="searchObj.status" class="select-shop-item" style="width:180px" @on-change='search'>
              <Option v-for="(item, i) in shopState" :value="item" :key="i">{{ item }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <Button class="search-btn" type="primary"  @click="doSearch">查询</Button>
          </Col>
          <Col class="search-item">
            <Button class="search-btn" @click="doReset">重置</Button>
          </Col>
        </Row>
        <Row type="flex" style="padding-right:16px">
          <Col>
            <div id="btn-export">
              <Row type="flex" justify="end" style="width:100%;padding-right:16px">
                <Col class="search-item">
                  <Button class="search-btn" @click='skipLead'>导入</Button>
                </Col>
                <Col class="search-item">
                  <Button class="search-btn" @click='exportData'>导出</Button>
                </Col>
              </Row>
            </div>
          </Col>
          <Col class="search-item">
            <Button v-if="exampleShow" @click="exampleOpen">收起筛选
              <Icon type="ios-arrow-up" />
            </Button>
            <Button v-else @click="exampleOpen">更多筛选
              <Icon type="ios-arrow-down" />
            </Button>
          </Col>
        </Row>
      </Row>
      <div class="search-example" v-show="exampleShow">
        <Row type="flex">
          <Col class="search-item">
            <span class="search-label">片区：</span>
            <Select v-model="area" style="width:180px" @on-change='search'>
              <Option :value="-1">全部</Option>
              <Option v-for="item in areaList" :value="item.orgName" :key="item.id">{{ item.orgName }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">品牌：</span>
            <Select v-model="brand" style="width:180px" @on-change='search'>
              <Option :value="-1">全部</Option>
              <Option v-for="item in brandList" :value="item.brandId" :key="item.brandId">{{ item.brandName }}</Option>
            </Select>
          </Col>
          <Col class="treeselect_box"
               style="margin-left: 30px">
          <span class="search-label"
                style="margin-right: 8px">业务标签：</span>
          <treeselect class="list_treeselect" :limit='1' :limitText='limitText'
                      style="width:200px;"
                      :multiple="true"
                      v-model='tagList'
                      noResultsText="未搜索符合的标签"
                      :options="options"
                      :normalizer="normalizer"
                      :value-consists-of="valueConsistsOf"
                      @input='selectList'
                      placeholder="请选择" />
          </Col>
        </Row>
      </div>
      <div id="btn-export-show">
        <Row type="flex" justify="end" style="width:100%;padding-right:16px">
          <Col class="search-item">
            <Button class="search-btn" @click='skipLead' v-if="hasPermission('moms:shop:import')">导入</Button>
          </Col>
          <Col class="search-item">
            <Button class="search-btn" @click='exportData' v-if="hasPermission('moms:shop:export')">导出</Button>
          </Col>
        </Row>
      </div>
    </div>
    <Modal title="业务标签" width='520' v-model="modalShow" :transfer='false'>
      <div style="border-bottom-left-radius: 6px;border-bottom-right-radius: 6px;overflow: hidden;">
        <Table :columns="modalColumns" :data="modalTableData" :max-height='480'></Table>
      </div>
      <div slot="footer"></div>
    </Modal>
    <Table :loading="loading"
           :max-height="520"
           ref="selection"
           :columns="columns"
           :data="shopList.shopListData"
           stripe
           class="table-list"
           @on-selection-change="onSelectionChange">
      <template slot-scope="{ row }" slot="tagSum">
        <p class="active" @click='openModal(row)'>{{ row.tagSum }}</p>
      </template>
      <template slot-scope="{ row }" slot="name">
        <p class='collection-productdesc'>{{ row.shopName }}</p>
      </template>
      <template slot-scope="{ row }" slot="desc">
        <p class='collection-productdesc'>{{ row.address }}</p>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <i class="iconsys icondetail" title="查看详情" @click='skipDetail(row, index)' v-if="hasPermission('moms:shop:detail')"></i>
        <i class="iconsys iconedit" title="编辑" @click='skipEdit(row, index)' v-if="hasPermission('moms:shop:update')"></i>
        <i class="iconsys iconsetting" title="设置" @click='skipSetting(row, index)' v-if="hasPermission('moms:setting:view')"></i>
        <i class="iconsys iconshengchengerweima" title="生成二维码" @click='skipCode(row, index)' v-if="hasPermission('moms:shop:genqrcode')"></i>
      </template>
    </Table>
    <div class="page-box">
      <Page :total="shopList.shopListTotal"
            ref="pages"
            :current="searchObj.offset"
            :page-size="searchObj.limit"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            show-total />
    </div>
  </div>
</template>
<script>
import { blobToXls } from '@/libs/blobToXls'
import { getDicQuery } from '@/api/setting'
import { brandList, tagTree } from '@/api/system/tag'
import { getCountList, shopStatusUpd, exportShop, getAreaList } from '@/api/system/store'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'store_list',
  components: { Treeselect },
  data () {
    return {
      modalTableData: [],
      modalColumns: [
        {
          title: '序号',
          type: 'index'
        },
        {
          title: '标签分组',
          key: 'parentName'
        },
        {
          title: '业务标签',
          key: 'name'
        }
      ],
      modalShow: false,
      tagList: null,
      exampleShow: false,
      searchShopName: '',
      loading: true,
      shopName: '',
      area: -1,
      type: '全部',
      brand: -1,
      areaList: [],
      brandList: [],
      typeList: [],
      shopState: [],
      columns: [
        {
          title: '门店名称',
          slot: 'name'
        },
        {
          title: '类型',
          key: 'shopProperty'
        },
        {
          title: '状态',
          key: 'status'
        },
        {
          title: '片区',
          key: 'areaName'
        },
        {
          title: '区域',
          key: 'regionName'
        },
        {
          title: '所属品牌',
          key: 'brandName'
        },
        {
          title: '机台/刷卡器/一体机数量',
          width: 170,
          key: 'countSum'
        },
        {
          title: '业务标签',
          slot: 'tagSum'
        }
      ],
      options: [],
      valueConsistsOf: 'ALL',
      normalizer (node) {
        if (node.shopTags) {
          if (node.shopTags.length > 0) {
            return {
              id: node.shopTagId,
              label: node.shopTagName,
              children: node.shopTags
            }
          } else {
            return {
              id: node.shopTagId,
              label: node.shopTagName,
              isDisabled: node.level === 2 ? '' : true
            }
          }
        }
      },
      searchObj: {
        merchantId: this.$store.state.user.merchantId,
        searchKey: '',
        offset: 1,
        limit: 10,
        status: '全部'
      },
      shopList: {
        shopListData: [],
        shopListTotal: 0
      },
      shopSelection: '', // 选择的门店信息
      shopIds: '', // 门店id
      theStoreStatus: ''// 当前门店状态
    }
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'store_list') {
        this.getShopListLoad()
      }
    }
  },
  created () {
    this.getAreaList()
    this.getStoreType()
    this.getBrand()
    this.getTag()
    this.getShopListLoad({ offset: 0 })
    if (this.hasPermission(['moms:shop:detail', 'moms:shop:update', 'moms:setting:view'])) {
      this.columns.push({
        title: '操作',
        width: 180,
        slot: 'action'
      })
    }
  },
  methods: {
    // 导出
    exportData () {
      exportShop({
        fileName: 'shop',
        type: 'EXCEL'
      }).then(res => {
        if (res.status === 200) {
          blobToXls(res.data, '导出门店列表')
        } else {
          this.$Message.error(res.message || res.error || res.err)
        }
      })
    },
    // 获取片区
    getAreaList () {
      getAreaList({
        orgName: '',
        orgType: '3'
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.areaList = result.data.data || []
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取品牌
    getBrand () {
      brandList({ merchantId: this.$store.state.user.merchantId }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.brandList = result.data || []
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取类型、状态
    getStoreType () {
      getDicQuery({
        dictKeys: 'shopType,shopStatus',
        merchantId: this.$store.state.user.merchantId,
        msType: '0'
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          if (result.data[0].shopType + '' !== '0') {
            this.typeList = ['全部'].concat(result.data[0].shopType.split('|') || [])
          }
          if (result.data[1].shopStatus + '' !== '0') {
            this.shopState = ['全部'].concat(result.data[1].shopStatus.split('|') || [])
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取业务标签
    getTag () {
      tagTree({ tagStatus: '1', level: 1, merchantId: this.$store.state.user.merchantId }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.options = result.data
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    limitText () {
      return '...'
    },
    selectList (data) {
      this.tagList = data.length > 0 ? data : null
      this.getShopListLoad({ offset: 0 })
      this.searchObj.offset = 0
    },
    // 筛选按钮筛选按钮
    exampleOpen () {
      this.exampleShow = !this.exampleShow
    },
    changeSwitch (row, index) {
      this.shopIds = row.shopId
      this.theStoreStatus = row.status
      this.updShopState(row.status)
    },
    filterSpace () {
      this.searchObj.searchKey = this.searchObj.searchKey ? this.searchObj.searchKey.replace(/\s+/g, '') : ''
    },
    changeStatus (val) {
      this.searchObj.offset = 1
      this.searchObj.status = val === '-1' ? '' : val
      this.getShopListLoad({ offset: (this.searchObj.offset - 1) * this.searchObj.limit })
    },
    skipCode (row, index) {
      this.$router.push({ name: 'store_qrcode', params: { id: row.shopId }, query: { sn: row.partnerSign } })
    },
    skipDetail (row, index) {
      this.$router.push({ name: 'store_detail', params: { id: row.shopId } })
    },
    skipEdit (row, index) {
      this.$router.push({ name: 'store_edit', params: { id: row.shopId } })
    },
    skipSetting (row, index) {
      this.$router.push({ name: 'store_setting', params: { id: row.shopId } })
      localStorage.setItem('keyValue', row.shopId)
    },
    skipLead () {
      this.$router.push({ name: 'store_import' })
    },
    search () {
      this.searchObj.offset = 1
      this.getShopListLoad({ offset: 0 })
    },
    openModal (row) {
      this.modalShow = true
      this.modalTableData = []
      if (row.tagLevels.length > 0) {
        row.tagLevels.forEach(item => {
          if (item.tagList.length > 0) {
            item.tagList.forEach(val => {
              this.modalTableData.push({ id: val.shopTagId, name: val.shopTagName, parentName: item.shopTagName })
            })
          }
        })
      }
    },
    doSearch () {
      this.searchShopName = this.searchObj.searchKey
      this.searchObj.offset = 1
      this.getShopListLoad({ offset: 0 })
    },
    doReset () {
      this.searchShopName = ''
      this.searchObj = {
        merchantId: this.$store.state.user.merchantId,
        searchKey: '',
        offset: 1,
        limit: 10,
        status: '全部'
      }
      this.tagList = null
      this.brand = -1
      this.type = '全部'
      this.area = -1
      this.searchObj.offset = 1
      this.getShopListLoad({ offset: 0 })
    },
    handlePage (val) {
      this.searchObj.offset = val
      this.getShopListLoad({ offset: (val - 1) * this.searchObj.limit })
    },
    handlePageSize (val) {
      this.searchObj.limit = val
      this.getShopListLoad({ offset: (this.searchObj.offset - 1) * this.searchObj.limit })
    },
    getShopListLoad (res) {
      this.loading = true
      getCountList({
        ...this.searchObj,
        status: this.searchObj.status === '全部' ? '' : this.searchObj.status,
        shopTagList: this.tagList, // 业务标签
        brandId: this.brand === -1 ? '' : this.brand, // 品牌
        shopProperty: this.type === '全部' ? '' : this.type, // 门店性质
        areaName: this.area === -1 ? '' : this.area, // 片区
        searchKey: this.searchShopName,
        offset: (this.searchObj.offset - 1) * this.searchObj.limit,
        ...res
      }).then(res => {
        if (res.data.status === 200) {
          this.shopList.shopListData = res.data.data
          this.shopList.shopListTotal = res.data.totalCount
          this.loading = false
        } else {
          this.$Message.error('加载失败！')
          this.loading = false
        }
      }).catch((error) => {
        this.$Message.error(`${this.showError(error)}`)
        this.loading = false
      })
    },
    handleSelectAll (status) {
      this.$refs.selection.selectAll(status)
    },
    dropClick (state) {
      if (this.shopSelection.length > 0) {
        this.shopIds = this.getShopId().join(',')
        this.updShopState(state)
      } else {
        this.$Message.error('请至少选择一条数据操作')
      }
    },
    onSelectionChange (selection) {
      this.shopSelection = selection
    },
    updShopState (state) {
      shopStatusUpd({
        'merchantId': this.$store.state.user.merchantId,
        'shopId': this.shopIds,
        'status': state === '-1' ? '' : state ? '1' : '0'
      }).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('操作成功！')
        } else {
          this.$Message.error('操作失败！' + `${res.data.error}`)
        }
      }).catch((error) => {
        this.$Message.error(`${this.showError(error)}`)
      })
    },
    getShopId () {
      return this.shopSelection.map(item => {
        return item.shopId
      })
    },
    showError (error) {
      return error.response && error.response.data.message ? error.response.data.message : (error.data && error.data.message ? error.data.message : '')
    }
  }
}
</script>

<style lang='less'>
#shop-list {
  .ivu-input-group-prepend,
  .ivu-input-group-append {
    background: #fff !important;
    border: 0 !important;
  }
  .table-show {
    margin-top: 20px;
    .ivu-table-border th,
    .ivu-table-border td {
      text-align: center !important;
    }
  }
  .table-list {
    .collection-productdesc {
      max-height: 38px;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
  }
  .active {
    color: #2d8cf0;
    cursor: pointer;
  }
  .ivu-modal-body {
    padding: 0;
  }
  .ivu-modal-footer {
    border-top: 0;
    padding: 0;
  }
  .ivu-modal-header {
    border-bottom: 0;
  }
  .treeselect_box {
    display: flex;
    align-items: center;
    margin-left: 30px;
    padding-top: 24px;
    span {
      margin-right: 8px;
    }
  }
  .vue-treeselect__multi-value {
    line-height: normal;
    margin-bottom: 0px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .vue-treeselect__multi-value-label {
    line-height: normal;
    margin-bottom: 0px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    max-width: 80px;
  }
  .vue-treeselect__limit-tip {
    padding-top: 0px;
  }
  .vue-treeselect__multi-value-item-container {
    padding-top: 5px;
  }
  .vue-treeselect__multi-value-item {
    cursor: pointer;
    display: inline-table;
    background: #e3f2fd;
    padding: 0 0;
    border: 1px solid transparent;
    border-radius: 2px;
    color: #039be5;
    font-size: 12px;
    vertical-align: top;
  }
  .vue-treeselect__menu-container {
    width: 200px;
  }
}
</style>
